package com.yuexunit.account.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;
import com.yuexunit.util.encode.MD5Encoder;

import java.util.Date;


/**
 * 帐号密码 
 * @author wangjinshui
 */
@Entity
@Table(name="AC_ACCOUNT_PASSWORD")
//@Cacheable(maxCount=5000, timeToIdleSeconds=36000)
public class AccountPasswordEntity {
	@Id
	@Column(name="ACCOUNT_ID")
	private Long accountId;

	@Column(name="PASSWORD_MD5")
	private String password;

	@Column(name="RANDOM_CODE")
	private String randomCode;

	@Column(name="ENABLED")
	private Boolean enabled;
	
	@Column(name="CREATE_DT")
	private Date createDate;
	
	
	public AccountPasswordEntity() {
	}
	
	public AccountPasswordEntity(Long accountId, String password) {
		this.accountId = accountId;
		initRandomCode();
		initPasswordSalted(password);
		this.enabled = Boolean.TRUE;
		initCreateDate();
	}
	
	
	public Long getAccountId() {
		return accountId;
	}

	public void setAccountId(Long accountId) {
		this.accountId = accountId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRandomCode() {
		return randomCode;
	}

	public void setRandomCode(String randomCode) {
		this.randomCode = randomCode;
	}
	
	public Boolean getEnabled() {
		return enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	
	/**
	 * 生成4位随机码
	 */
	public void initRandomCode() {
		setRandomCode(StringUtil.randomCode4Digits());
	}
	
	/**
	 * 将输入的密码加盐后，设置为MD5密码
	 * @param password 原始密码
	 */
	public void initPasswordSalted(String password) {
		setPassword(MD5Encoder.encode(password + getRandomCode()));
	}
	
	/**
	 * 设置创建时间为当前时间。
	 */
	public void initCreateDate() {
		setCreateDate(DateUtil.now());
	}
	
	/**
	 * @param password 密码
	 * @return 判断输入的密码加盐后与服务器的密码相同则返回true；否则返回false。
	 */
	public boolean correctPassword(String password) {
		if (password == null)
			return false;
		
		String passwordSalted = MD5Encoder.encode(password + getRandomCode());
		return passwordSalted.equals(getPassword());
	}
	
	

	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		
		result.append(getClass().getName())
			.append(": accountId=").append(accountId)
			.append(", password='").append(password).append("'")
			.append(", randomCode='").append(randomCode).append("'")
			.append(", createDate=").append(createDate)
			;
		
		return result.toString();
	}
}
